package com.shop.zdy.filter;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shop.zdy.bo.Cart;

public final class EncodingFilter implements Filter{
	private String encoding;
	private boolean ignore;
	public EncodingFilter(){
		encoding="utf-8";
		ignore=false;
	}
	public void init(FilterConfig config){
		if(config.getInitParameter("encoding")!=null)
			encoding=config.getInitParameter("encoding");
		if(config.getInitParameter("ignore")!=null)
			ignore=(new Boolean(config.getInitParameter("ignore"))).booleanValue();
	}
	public void doFilter(ServletRequest request,ServletResponse response,
			FilterChain chain) throws IOException,ServletException{
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse res=(HttpServletResponse)response;
		if(!ignore){
			req.setCharacterEncoding(encoding);
			res.setCharacterEncoding(encoding);
		}
		
		HttpSession session = req.getSession();
		Cart cart = (Cart) session.getAttribute("mcCart");
		if (cart == null) {
			cart = new Cart();
			session.setAttribute("mcCart", cart);
		}
		String basePath = req.getScheme() + "://" + req.getLocalName()
				+ ":" + req.getLocalPort() + req.getContextPath() + "/";
		req.setAttribute("basePath", basePath);
		
		chain.doFilter(request,response);
	}
	public void destroy(){
		
	}
}
